<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/17 0017
 * Time: 11:57
 */
namespace app\common\controller;

use think\Controller;
use app\api\traits\Wechat;

class WeChatSms extends Controller
{
    use Wechat;
    /**
     * 微信发送模板消息
     * @param $touser
     * @param $template_id
     * @param $url
     * @param $data
     * @param string $topcolor
     * @return bool
     * */
    public function sendWxTemplateMessage($touser,$template_id,$url,$data,$topcolor){
        $access_token = $this->getWxAccess_Token();
        //模板消息
        $template=array(
            'touser' => $touser,
            'template_id'=> $template_id,
            'url'=> $url,
            'topcolor'=> $topcolor,
            'data'=> $data,
        );
        $json_template=json_encode($template);
        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $dataRes=$this->http_request($url,urldecode($json_template));
    }

    /**
     * 获取微信公共的access_token
     * */
    public function getWxAccess_Token($qiangzhi=false){
        //获取access_token
        return $this->getaccesstoken($qiangzhi);
    }

    /**
     * 发送一个请求post
     * @param $url
     * @param array $data
     * @return mixed
     */
    function http_request($url, $data=array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // 我们在POST数据哦！
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}